//
//  ViewController.swift
//  I.S.A.P WT
//
//  Created by Илья Проскурнев on 09.05.2020.
//  Copyright © 2020 Илья Проскурнев. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

        @IBOutlet weak var cutsys: UIButton!
        @IBOutlet weak var freestyle: UIButton!
    
        
        var idhostTextField: UITextField?
        var sudTextField: UITextField?
        var passConfim: UITextField?
        
        var idhost = ""
        var idvistuplenie: Int?
        
        var URL_KORT: String?
        let URL_KORT2 = "/php_isap/sud/conn_kort.php"
        
        var URL_SUD: String?
        let URL_SUD2 = "/php_isap/sud/conn_set.php"
        
        var URL_CON: String?
        let URL_CON2 = "/php_isap/sud/conn_while.php"
        
        var data = Data()
        var kolSud: Int!
        var nomKort: Int!
        var kolSudConn: Int!
        var idSett: Int!
        
        var sud1 = 0
        var sud2 = 0
        var sud3 = 0
        var sud4 = 0
        var sud5 = 0
        var sud6 = 0
        var sud7 = 0
        var sudNum: Int!
        var sys, success: Int!
        var sudArray: NSArray!
        
        var vistocen: Int!
        
        var defaults = UserDefaults.standard
        
        @IBOutlet weak var para: UIButton!
        
        @IBOutlet weak var kortName: UILabel!
        @IBOutlet weak var sudName: UILabel!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            self.navigationItem.setHidesBackButton(true, animated: true)
            // Do any additional setup after loading the view, typically from a nib.
            cutsys.isEnabled = false
            freestyle.isEnabled = false
            
        }
        
        
        @IBAction func setting(_ sender: Any) {
            let alert = UIAlertController(title: "Settings", message: "Joystick", preferredStyle: UIAlertController.Style.alert)
            alert.addAction(UIAlertAction(title: "Apply", style: UIAlertAction.Style.default, handler: { (action) -> Void in
                // Now do whatever you want with inputTextField (remember to unwrap the optional)
                if (self.idhostTextField?.text == "") {
                    self.present(alert, animated: true, completion: nil)
                } else {
                    self.idhost = (self.idhostTextField?.text)!
                    if (self.idhost == "2912") {
                        self.idhost = "https://poomsae.ru/cpt"
                        self.defaults.set(self.idhostTextField?.text, forKey: "idhost")
                        DispatchQueue.main.async {
                            self.kort()
                        }
                    } else {
                        self.defaults.set(self.idhostTextField?.text, forKey: "idhost")
                        self.idhost = "http://" + (self.idhostTextField?.text)!
                        print("idhost = ", self.idhost)
                        self.kort()
                    }
                }
            }));
            
            alert.addTextField(configurationHandler: {(textField: UITextField!) in
                textField.placeholder = "IP сервера"
                if (self.defaults.string(forKey: "idhost") != "") { textField.text = self.defaults.string(forKey: "idhost") } else {
                    textField.isSecureTextEntry = false
                }
                self.idhostTextField = textField
            });
            self.present(alert, animated: true, completion: nil)
        }
        
        func kort() {
            URL_KORT = idhost + URL_KORT2
            let url: URL = URL(string: self.URL_KORT ?? "")!
            let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
            let task = defaultSession.dataTask(with: url) { (data, response, error) in
                if error != nil {
                    print("Failed to download data")
                } else {
                    print("kort else")
                    self.parseJSONKort(data!)
                }
            }
            task.resume()
        }
        
        func parseJSONKort(_ data:Data) {
            print("parseJSONKort")
            var jsonResult = NSDictionary()
            do {
                jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                let kortArray = (jsonResult["kort"] as! NSArray)
                var kort = NSDictionary()
                kort = kortArray[0] as! NSDictionary
                self.nomKort = Int ((kort["kort"] as! NSString) as String)
                self.kolSud = Int ((kort["kol"] as! NSString) as String)
                self.idSett = Int ((kort["ids"] as! NSString) as String)
                self.kolSudConn = Int (truncating: (kort["kolconn"] as! NSNumber))
                self.sys = Int ((kort["sys"] as! NSString) as String)
                if(self.nomKort != 0) {
                    print("self.nomKort")
                    DispatchQueue.main.async {
                        self.viborKort()
                    }
                }
                
            } catch let error as NSError {
                print(error)
            }
            
        }
        
        func viborKort() {
            print("viborKort")
            let ac = UIAlertController(title: "Настройки", message: "Корт", preferredStyle: UIAlertController.Style.alert)
            let kort1 = UIAlertAction(title: "Корт 1", style: .default) { (_) in
                self.kortName.text = "Корт № " + String(self.nomKort!)
                DispatchQueue.main.async {
                    self.downloadSud()
                }
            }
            
            if (nomKort != 1 || kolSudConn == kolSud) {
                kort1.isEnabled = false
            }
            
            let kort2 = UIAlertAction(title: "Корт 2", style: .default) { (_) in
                self.kortName.text = "Корт № " + String(self.nomKort!)
                DispatchQueue.main.async {
                    self.downloadSud()
                }
            }
            
            if (nomKort != 2 || kolSudConn == kolSud) {
                
                kort2.isEnabled = false
                
            }
            
            let kort3 = UIAlertAction(title: "Корт 3", style: .default) { (_) in
                self.kortName.text = "Корт № " + String(self.nomKort!)

                DispatchQueue.main.async {
                    self.downloadSud()
                }
            }
            
            if (nomKort != 3 || kolSudConn == kolSud) {
                
                kort3.isEnabled = false
                
            }
            
            let cancel = UIAlertAction(title: "Отмена", style: .cancel) { (_) in
                
            }
            
            ac.addAction(kort1)
            ac.addAction(kort2)
            ac.addAction(kort3)
            ac.addAction(cancel)
            self.present(ac, animated: true)
            
        }
        
        func sudVibor()  {
            
            let ac = UIAlertController(title: "Настройки", message: "Судья", preferredStyle: UIAlertController.Style.alert)
            let sudNum1 = UIAlertAction(title: "Судья 1", style: .default) { (_) in
                self.sudNum = 1
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum2 = UIAlertAction(title: "Судья 2", style: .default) { (_) in
                self.sudNum = 2
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum3 = UIAlertAction(title: "Судья 3", style: .default) { (_) in
                self.sudNum = 3
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum4 = UIAlertAction(title: "Судья 4", style: .default) { (_) in
                self.sudNum = 4
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum5 = UIAlertAction(title: "Судья 5", style: .default) { (_) in
                self.sudNum = 5
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum6 = UIAlertAction(title: "Судья 6", style: .default) { (_) in
                self.sudNum = 6
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            let sudNum7 = UIAlertAction(title: "Судья 7", style: .default) { (_) in
                self.sudNum = 7
                self.sudName.text = "Судья № " + String(self.sudNum!)
                DispatchQueue.main.async {
                    self.whiteSud()
                    self.system()
                }
            }
            
            if (self.sud1 != 0) { sudNum1.isEnabled = false }
            if (self.sud2 != 0) { sudNum2.isEnabled = false }
            if (self.sud3 != 0) { sudNum3.isEnabled = false }
            if (self.sud4 != 0) { sudNum4.isEnabled = false }
            if (self.sud5 != 0) { sudNum5.isEnabled = false }
            if (self.sud6 != 0) { sudNum6.isEnabled = false }
            if (self.sud7 != 0) { sudNum7.isEnabled = false }
            
            switch (self.kolSud) {
                
            case 1:
                ac.addAction(sudNum1)
                break
                
            case 3:
                ac.addAction(sudNum1)
                ac.addAction(sudNum2)
                ac.addAction(sudNum3)
                break
                
            case 5:
                ac.addAction(sudNum1)
                ac.addAction(sudNum2)
                ac.addAction(sudNum3)
                ac.addAction(sudNum4)
                ac.addAction(sudNum5)
                break
                
            case 7:
                ac.addAction(sudNum1)
                ac.addAction(sudNum2)
                ac.addAction(sudNum3)
                ac.addAction(sudNum4)
                ac.addAction(sudNum5)
                ac.addAction(sudNum6)
                ac.addAction(sudNum7)
                break
                
            default: break
                
            }
            self.present(ac, animated: true)
        }
        
        func downloadSud() {
            
            self.URL_SUD = self.idhost + self.URL_SUD2
            let requestURL = NSURL(string: URL_SUD ?? "")
            let request = NSMutableURLRequest(url: requestURL! as URL)
            request.httpMethod = "POST"
            let postParameters = "ids=" + String (self.idSett)
            request.httpBody = postParameters.data(using: String.Encoding.utf8)
            
            var myJSON = NSDictionary()
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in
                //parsing the response
                do {
                    //converting resonse to NSDictionary
                    myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                    self.sudArray = (myJSON["kolsud"] as! NSArray)
                    var sudJSON = NSDictionary()
                    if (self.sudArray.count != 0) {
                        for i in 0...self.sudArray.count-1 {
                            sudJSON = self.sudArray[i] as! NSDictionary
                            let sudCon = Int ((sudJSON["conn_sud"] as! NSString) as String) ?? 0
                            switch (sudCon)  {
                            case 1: self.sud1 = sudCon; break
                            case 2: self.sud2 = sudCon; break
                            case 3: self.sud3 = sudCon; break
                            case 4: self.sud4 = sudCon; break
                            case 5: self.sud5 = sudCon; break
                            case 6: self.sud6 = sudCon; break
                            case 7: self.sud7 = sudCon; break
                            default: break
                                
                            }
                            
                        }
                        
                    }
                    
                } catch {
                    print(error)
                }
                print(myJSON)
                DispatchQueue.main.async {
                    self.sudVibor()
                }
            }
            //executing the task
            task.resume()
            
        }
        
        func whiteSud() {
            self.URL_CON = self.idhost + self.URL_CON2
            let requestURL = NSURL(string: URL_CON ?? "")
            //creating NSMutableURLRequest
            let request = NSMutableURLRequest(url: requestURL! as URL)
            //setting the method to post
            request.httpMethod = "POST"
            var myJSON = NSDictionary()
            //creating the post parameter by concatenating the keys and values from text field
            let postParameters = "sud=" + String (self.sudNum) + "&ids=" + String(self.idSett)
            //adding the parameters to request body
            request.httpBody = postParameters.data(using: String.Encoding.utf8)
            //creating a task to send the post request
            let task = URLSession.shared.dataTask(with: request as URLRequest){
                data, response, error in
                //parsing the response
                do {
                    //converting resonse to NSDictionary
                    if (error != nil) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
                            self.whiteSud()
                        })
                    } else {
                        myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                        self.success = myJSON["success"] as? Int
                    }

                } catch {
                    print("err = ", error)
                }

            }
            task.resume()
        }
        
        func system() {
            switch(self.sys) {
                case 1: cutsys.isEnabled = true; cutsys.layer.backgroundColor = UIColor.green.cgColor; break
                case 4: freestyle.isEnabled = true; freestyle.layer.backgroundColor = UIColor.green.cgColor; break
                default: break
            }
            
        }
    
        override func prepare (for segue: UIStoryboardSegue, sender: Any?) {
            switch(self.sys) {
            case 1:
                let ocenController: OcenController = segue.destination as! OcenController
                ocenController.idhost = self.idhost
                ocenController.sudNum = self.sudNum
                ocenController.kolSud = self.kolSud
                ocenController.sys = self.sys
                ocenController.vistocen = self.vistocen;
                break
            case 2:
                let frestyleController: FreestyleController = segue.destination as! FreestyleController
                frestyleController.idhost = self.idhost
                frestyleController.sudNum = self.sudNum
                frestyleController.kolSud = self.kolSud
                frestyleController.sys = self.sys;
                break
            default: break
            }
        }
        
        func ocen() {
            let ac = UIAlertController(title: "Настройки", message: "Выставления оценок", preferredStyle: UIAlertController.Style.alert)
            let line = UIAlertAction(title: "Снятие свайпом", style: .default) { (_) in
                self.vistocen = 2
                let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ocenLineView") as! OcenController
                nextViewController.idhost = self.idhost
                nextViewController.sudNum = self.sudNum
                nextViewController.kolSud = self.kolSud
                nextViewController.vistocen = self.vistocen
                nextViewController.kort = self.nomKort
                nextViewController.sys = self.sys
                self.navigationController?.pushViewController(nextViewController, animated: true)
            }
            
            let button = UIAlertAction(title: "Снятие кнопками", style: .default) { (_) in
                self.vistocen = 1
                let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ocenButtonView") as! ButtonOcenController
                nextViewController.idhost = self.idhost
                nextViewController.sudNum = self.sudNum
                nextViewController.kolSud = self.kolSud
                nextViewController.vistocen = self.vistocen
                nextViewController.kort = self.nomKort
                nextViewController.sys = self.sys
                self.navigationController?.pushViewController(nextViewController, animated: true)
            }
            
            ac.addAction(line)
            ac.addAction(button)
            
            self.present(ac, animated: true)
            
        }
        @IBAction func system(_ sender: UIButton) {
            self.ocen()
        }

    @IBAction func houseBack(_ sender: Any) {
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "mainController") as! MainController
        self.navigationController?.pushViewController(nextViewController, animated: true)
    }
    
}

